package com.study.d2_dom4j_xml;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;

public class Test {
    public static void main(String[] args) throws Exception{
        //目标：使用dom4j框架解析XML文件
        //1、创建一个SaxReader解析器对象
        SAXReader saxReader = new SAXReader();

        //2、把xml文件读成一个document文档对象
        Document document = saxReader.read("day11/src/helloworld.xml");

        //3、文档对象中包含了xml的全部数据，提供了方法获取数据
        Element rootElement = document.getRootElement();
        System.out.println(rootElement.getName());
        System.out.println("==========");

        //4、提取子元素对象
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            System.out.println(element.getName() );
        }
        System.out.println("==========");
        List<Element> elements2 = rootElement.elements("user");
        for (Element element : elements2) {
            System.out.println(element.getName());
        }
        System.out.println("==========");
        Element user2 = rootElement.element("user2");
        System.out.println(user2.elementText("name"));

        System.out.println("==========");
        Element user = rootElement.element("user");
        Attribute idAttr = user.attribute("id");
        System.out.println(idAttr.getName());
        System.out.println(idAttr.getValue());
        System.out.println("==========");
        //直接拿属性
        System.out.println(user.attributeValue("id"));

        //文本值
        System.out.println(user.elementText("hobby"));
        //去掉空格
        System.out.println(user.elementTextTrim("hobby"));
        System.out.println("==========");
        Element name = user.element("name");
        System.out.println(name.getText());
    }
}
